//
//  HOUtils.m
//  WeiDu_1_0
//
//  Created by foguo-mac-1 on 01/07/16.
//  Copyright (c) 2016 WeiDu Energy Tech. All rights reserved.
//

#import "HOUtils.h"
#import "GTMStringEncoding.h"
#import "Logger.h"
#import <AudioToolbox/AudioToolbox.h>

@implementation HOUtils

static CGFloat screenWidth = 0;
static CGFloat screenHeight = 0;

static CGFloat statusBarHeight = 0;

#pragma mark - -- screen & status bar width/height

+ (CGFloat)getScreenWidth
{
    if(screenWidth != 0)
        return screenWidth;
    CGRect screenBound = [[UIScreen mainScreen] bounds];
    CGSize screenSize = screenBound.size;
    screenWidth = screenSize.width;
    return screenWidth;
}

+ (CGSize)getScreenSize
{
	CGRect screenBound = [[UIScreen mainScreen] bounds];
	CGSize screenSize = screenBound.size;
	return screenSize;
}


+ (CGFloat)getScreenHeight
{
    if(screenHeight != 0)
        return screenHeight;
    CGRect screenBound = [[UIScreen mainScreen] bounds];
    CGSize screenSize = screenBound.size;
    screenHeight = screenSize.height;
    return screenHeight;
}


+ (CGFloat)getStatusBarHeight
{
    if(statusBarHeight != 0)
        return statusBarHeight;
    CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
    statusBarHeight = statusBarFrame.size.height;
    return statusBarHeight;
}

#pragma mark

+ (CGFloat)defaultOnePixelConversion
{
    return 1.f / [UIScreen mainScreen].scale;
}
+ (UIImage *)createImageWithColor:(UIColor *)color forView:(UIView *)view
{
    CGRect rect = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

+ (UIImage *)createImageWithColor:(UIColor *)color forRect:(CGRect)rect
{
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}
+ (UIImage*)imageWithImage:(UIImage*)image
              scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}
+ (UIImage *)scaleImage:(UIImage *)image toScale:(CGSize)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(scaleSize.width, scaleSize.height));
    [image drawInRect:CGRectMake(0, 0, scaleSize.width, scaleSize.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

+ (NSTimeInterval) getCurrentTime
{
    return [[NSDate date] timeIntervalSince1970]; //second
}

//邮箱
+ (BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//身份证号
+ (BOOL) validateIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}


+ (BOOL)validePhoneNuber:(NSString *)number
{
    
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    //    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    //    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:number] == YES)
        || ([regextestcm evaluateWithObject:number] == YES)
        //        || ([regextestct number] == YES)
        || ([regextestcu evaluateWithObject:number] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
    return NO;
}
+ (CGFloat)getTitleWidth:(NSString *)title withFont:(UIFont *)font
{
    CGSize size = CGSizeZero;
    if(IS_LESSTHAN_IOS7)
    {
        size = [title sizeWithFont:font];
    }
    else
    {
        
        NSDictionary* dic = [NSDictionary
                             dictionaryWithObjectsAndKeys:
                             NSForegroundColorAttributeName,UIColorFromRGB(0xff0000),
                             font, NSFontAttributeName, nil];
        size = [title sizeWithAttributes:dic];
    }
    return size.width;
}


+ (NSString *)getEducationByIndex:(int)index
{
	switch (index) {
		case 0:
			return  NSLocalizedString(@"大专以下", @"大专以下");
 		 case 1:
			return NSLocalizedString(@"大专", @"大专");
		case 2:
			return  NSLocalizedString(@"本科", @"本科");
		case 3:
			return NSLocalizedString(@"硕士", @"硕士");
		case 4:
			return  NSLocalizedString(@"博士及以上", @"博士及以上");
		default:
			break;
	}
	return @"";
}


+ (NSString *)getDateFromTimeInterval:(NSTimeInterval)timeInterval
{
    if(timeInterval == 0)
        return @"";
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeInterval / 1000];
    
    NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
    
//	[formatter setDateFormat:@"yyyy-MM-d HH:mm:ss"];
	[formatter setDateFormat:@"yyyy-MM-d HH:mm"];
    NSTimeZone* timeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:timeZone];
    NSString* str = [formatter stringFromDate:date];
    return str;
}

+ (NSString *)getDateFromTimeInterval3:(NSTimeInterval)timeInterval
{
	if(timeInterval == 0)
		return @"";
	NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeInterval / 1000];
	
	NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
	
	[formatter setDateFormat:@"yy/MM/d HH:mm"];
	NSTimeZone* timeZone = [NSTimeZone localTimeZone];
	[formatter setTimeZone:timeZone];
	NSString* str = [formatter stringFromDate:date];
	return str;
}

+ (NSString *)getDateFromTimeIntervalChinese:(NSTimeInterval)timeInterval
{
	if(timeInterval == 0)
		return @"";
	NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeInterval / 1000];
	
	NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
	
//	[formatter setDateFormat:NSLocalizedString(@"yyyy年MM月d日 hh:mm a", @"yy年MM月d日 hh:mm a")];
	[formatter setDateFormat:@"yyyy/MM/d HH:mm"];
	NSTimeZone* timeZone = [NSTimeZone localTimeZone];
	[formatter setTimeZone:timeZone];
	NSString* str = [formatter stringFromDate:date];
	return str;
}

+ (NSString *)getDateFromTimeInterval4:(NSTimeInterval)timeInterval
{
	if(timeInterval == 0)
		return @"";
	NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeInterval / 1000];
	
	NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
	
	[formatter setDateFormat:@"yyyy/MM/dd"];
	NSTimeZone* timeZone = [NSTimeZone localTimeZone];
	[formatter setTimeZone:timeZone];
	NSString* str = [formatter stringFromDate:date];
	return str;
}

+ (NSString *)getDateFromTimeInterval2:(NSTimeInterval)timeInterval
{
    if(timeInterval == 0)
        return @"";
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeInterval / 1000];
    
    NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSTimeZone* timeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:timeZone];
    NSString* str = [formatter stringFromDate:date];
    return str;
}


+ (BOOL)validateDomain:(NSString *)domain
{
    return YES;
//    if(domain == nil || domain.length < 2)
//    {
//        return NO;
//    }
//    NSString *urlRegEx =
//    @"(([.]|[/])((\\w|-)+))+";
//    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
//    return [urlTest evaluateWithObject:domain];
}

+ (NSString*)base64Encode:(NSString*)text
{
    if( (text == nil) || ( [text length] == 0) )
        return nil;
    
    GTMStringEncoding* base64Encoding = [GTMStringEncoding rfc4648Base64StringEncoding];
    return [base64Encoding encodeString:text];
}

+ (NSString*)base64Decode:(NSString*)text
{
    if( (text == nil) || ( [text length] == 0) )
        return nil;
    
    
    GTMStringEncoding* base64Encoding = [GTMStringEncoding rfc4648Base64StringEncoding];
    return [base64Encoding stringByDecoding:text];
}

+ (UIFont *)fontWithSize:(CGFloat)size
{
    return [UIFont fontWithName:@"Helvetica Neue" size:size];
}



+ (NSString *)getValideString:(NSString *)string
{
	if(string == nil)
		return @"";
	if([string isKindOfClass:[NSNumber class]])
	{
		return string;
	}
	else if([string isKindOfClass:[NSNull class]]
	   || string.length == 0)
	{
		return @"";
	}
	else
	{
		return string;
	}
}

+ (UIColor *)getStatusColorOfTemplate:(int)status
{
    //(int 0:审核中 1:白名单 2:黑名单 3：等待审核)
    /*审核中 蓝色 #42a6f2
    白名单 绿色  #25ae5f
    黑名单 灰色  #999999
    等待审核 红色  #ff3e3e*/
    if(status == 0)
        return UIColorFromRGB(0x42a6f2);//审核中
    else if(status == 1)
        return UIColorFromRGB(0x25ae5f);//白名单
    else if(status == 2)
        return UIColorFromRGB(0x999999);//黑名单
    else if(status == 3)
        return UIColorFromRGB(0xff3e3e);//等待审核
    return UIColorFromRGB(0x42a6f2);
}
+(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
{
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
    }
    UIGraphicsEndImageContext();
    return newImage;
}

+ (NSString*)arrayToJson:(NSArray *)array

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease];
    
}
+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease];
    
}

+ (NSString*)getCurrentDateForFileName
{
    NSDate* date = [NSDate date];
    
    NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
    
    [formatter setDateFormat:@"[yyyy-MM-dd_HH_mm_ss]"];
    NSTimeZone* timeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:timeZone];
    NSString* str = [formatter stringFromDate:date];
    return str;
}

+ (NSString*)getCurrentDate
{
	NSDate* date = [NSDate date];
	
	NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
	
	[formatter setDateFormat:@"yyyy-MM-dd"];
	NSTimeZone* timeZone = [NSTimeZone localTimeZone];
	[formatter setTimeZone:timeZone];
	NSString* str = [formatter stringFromDate:date];
	return str;
}

+ (NSArray *)arrayWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil)
    {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    return array;
    
//    if(err) {
//        NSLog(@"json解析失败：%@",err);
//        return nil;
//    }
//    return array;
    
}

+ (NSString *)getTimestampFromString:(NSString *)timestampStr
{
	if(timestampStr == nil || timestampStr.length == 0)
		return @"0";
	NSMutableString *timeStr = [NSMutableString stringWithString:@""];
	
	NSArray *timestamps = [timestampStr componentsSeparatedByString:@";"];
	
	for(int i = 0; i < [timestamps count]; i ++)
	{
		double time = [[timestamps objectAtIndex:i] doubleValue];
		
		NSString *timeFormated = [HOUtils getDateFromTimeInterval3:time];
		
		if(i%2 == 0)
		{
			if(i == 0)
			{
				[timeStr appendFormat:@"%@", timeFormated];
			}
			else
			{
				[timeStr appendFormat:@"\n%@", timeFormated];
			}
		}
		else
		{
			[timeStr appendFormat:@" ~%@", timeFormated];
		}
		
	}
	
	return timeStr;
}

+ (NSString *)getL10WithRawString:(NSString *)rawString withKeyString:(NSString *)keyString
{
	return [rawString stringByReplacingOccurrencesOfString:@"X" withString:keyString];
}

+ (NSString *)getAgeFromBirthday:(NSString *)birthday
{
//	birthday = @"1982-02-07";
//	NSLog(@"birthday:%@", birthday);
	if(birthday == nil || birthday.length == 0)
		return @"0";
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
	[dateFormatter setDateFormat:@"yyyy"]; //生日
//	NSDate *birthday = [dateFormatter dateFromString:birthday]; //当前时间
	NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
	[dateFormatter release];
//	NSDate *currentDate = [dateFormatter dateFromString:currentDateStr];
//	NSLog(@"currentDate %@ birthday %@",currentDateStr,birthday);
//	NSTimeInterval time=[currentDate timeIntervalSinceDate:birthday];
	int age = [currentDateStr intValue] - [birthday intValue] + 1;
//	NSLog(@"year %d",age);
	return [NSString stringWithFormat:@"%d", MAX(0, age)];
}


+ (void)playMidi
{
	AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
	AudioServicesPlaySystemSound(1007);
}

+ (void)removeFromSuperViewForViews:(UIView *)view, ...
{
	
	//指向变参的指针
	va_list list;
	//使用第一个参数来初使化list指针
	va_start(list, view);
	while (YES)
	{
		//返回可变参数，va_arg第二个参数为可变参数类型，如果有多个可变参数，依次调用可获取各个参数
		UIView *subView = va_arg(list, UIView*);
		if (!subView) {
			break;
		}
//		if(subView != nil &&[subView isKindOfClass:[UIView class]] && [subView superview] != nil)
//		{
////			[subView removeFromSuperview];
//		}
	}
	//结束可变参数的获取
	va_end(list);

}

#pragma mark - -- local folder and file.

+ (NSString*)getDocumentDirectory
{
	static NSString* s_globalRootDocDir = nil;
	if(s_globalRootDocDir == nil)
	{
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		s_globalRootDocDir = [[NSString alloc]initWithString:[paths firstObject]];
	}
	
	NSString* rootDoc = [[[NSString alloc] initWithString:s_globalRootDocDir] autorelease];
	return rootDoc;
}
+ (NSString *)getFilePathWithFileName:(NSString *)fileName withFolderPath:(NSString *)folderPath withExtension:(NSString *)ext
{
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if (![fileManager fileExistsAtPath:folderPath])
	{
		[fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
	}
	//    LogNor(@"folderPath, %@", folderPath);
	//    LogNor(@"fileName, %@", fileName);
	//    LogNor(@"ext, %@", ext);
	NSString * filePath = [NSString stringWithFormat:@"%@%@.%@", folderPath, fileName, ext];
	return filePath;
}

+ (NSString *)getVoiceFilePathWithFileName:(NSString *)fileName
{
	NSString *fileFolder = [HOUtils getVoiceFolderPath];
	if(fileFolder == nil)
	{
		LogWar(@"fileFolder == nil");
		return nil;
	}
	NSString *filePath = [NSString stringWithFormat:@"%@%@", fileFolder, fileName];
	return filePath;
}

+ (NSString *)getVoiceFolderPath
{
	return [NSString stringWithFormat:@"%@/voice/",[HOUtils getUserFolderPath]];
}

+ (NSString *)getUserFolderPath
{
	NSString* documentDic = [HOUtils getDocumentDirectory];
	if(documentDic == nil)
	{
		LogWar(@"documentDic == nil");
		return @"";
	}
	NSString *folder = [NSString stringWithFormat:@"user_%@", @"record"];
	NSString* path = [NSString stringWithFormat:@"%@/%@", documentDic, folder];
	return [HOUtils getValideString:path];
}

+ (NSString *)getWavAudioFolderPath
{
	return [NSString stringWithFormat:@"%@/voice/wav/",[HOUtils getUserFolderPath]];
}

+ (BOOL)isExistFileInLocal:(NSString *)filePath
{
	if(filePath == nil || filePath.length == 0)
		return NO;
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	return [fileManager fileExistsAtPath:filePath];
}

+ (BOOL)deleteAudioFromLocal:(NSString *)fileName withFileType:(NSString *)fileType
{
	NSString *filePath;
//	if ([fileType isEqualToString:FILE_TYPE_WAV ])
//	{
//		filePath = [HOUtils getFilePathWithFileName:fileName withFolderPath:[HOUtils getWavAudioFolderPath] withExtension:fileType];
//	}
//	else
//	{
//		filePath = [HOUtils getFilePathWithFileName:fileName withFolderPath:[HOUtils getVoiceFolderPath] withExtension:fileType];
//	}
	filePath = [HOUtils getFilePathWithFileName:fileName withFolderPath:[HOUtils getVoiceFolderPath] withExtension:fileType];
//	LogNor(@"filePath: %@", filePath);
	if(![self isExistFileInLocal:filePath])
		return YES;
	NSError *error;
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if (![fileManager removeItemAtPath:filePath error:&error])
	{
		LogNor(@"Error removing auido file: %@", error);
		return NO;
	}
	else
	{
		return YES;
	}
	return NO;
}

+ (NSArray *)getReportOrderStatus
{
	return [NSArray arrayWithObjects:[NSNumber numberWithInt:HO_REPORT_ORDER_ALL],
			[NSNumber numberWithInt:HO_REPORT_ORDER_UNACCEPT],
			[NSNumber numberWithInt:HO_REPORT_ORDER_ACCEPTED],
			[NSNumber numberWithInt:HO_REPORT_ORDER_REPAIRED],
			[NSNumber numberWithInt:HO_REPORT_ORDER_CONFIRMED],
			nil];
}

+ (NSString *)getDescribtionWithStatus:(HO_REPORT_ORDER_STATUS)status
{
	//【1:未处理2:已处理3:维修完成4:确认完成】
	switch (status)
	{
		case HO_REPORT_ORDER_ALL:
		case HO_EXTRA_ASS_ORDER_ALL:
			return NSLocalizedString(@"所有", @"所有");
  		case HO_REPORT_ORDER_UNACCEPT:
			return NSLocalizedString(@"未受理", @"未受理");
		case HO_REPORT_ORDER_ACCEPTED:
			return NSLocalizedString(@"已受理", @"已受理");
  		case HO_REPORT_ORDER_REPAIRED:
			return NSLocalizedString(@"维修完成", @"维修完成");
  		case HO_REPORT_ORDER_CONFIRMED:
		case HO_EXTRA_ASS_ORDER_CONFIRMED:
			return NSLocalizedString(@"确认完成", @"确认完成");
		case HO_EXTRA_ASS_ORDER_REPAIRED:
			return NSLocalizedString(@"维修完成", @"维修完成");
		case HO_REPORT_ORDER_UNCOMPLETED:
		case HO_EXTRA_ASS_ORDER_CHECK_UNCOMPLETE:
			return NSLocalizedString(@"未维修完成", @"未维修完成");
		case HO_EXTRA_ASS_ORDER_UNCHECK:
			return NSLocalizedString(@"未审核", @"未审核");
		case HO_EXTRA_ASS_ORDER_DIR_CHECK:
			return NSLocalizedString(@"主任审核通过", @"主任审核通过");
		case HO_EXTRA_ASS_ORDER_DEAN_CHECK:
			return NSLocalizedString(@"院长审核通过", @"院长审核通过");
		case HO_EXTRA_ASS_ORDER_CHECK_FAILED:
			return NSLocalizedString(@"审核失败", @"审核失败");
			
		default:
			return @"";
	}
	return @"";
}

+ (UIColor *)getOrderColorWithStatus:(HO_REPORT_ORDER_STATUS)status
{
	//【1:未处理2:已处理3:维修完成4:确认完成】
	switch (status)
	{
		case HO_REPORT_ORDER_ALL:
		case HO_EXTRA_ASS_ORDER_ALL:
			return UIColorFromRGB(0xc2c2c2);
		case HO_EXTRA_ASS_ORDER_UNCHECK:    		//未审核(外协)
		case HO_REPORT_ORDER_UNACCEPT:    			//未处理
			return UIColorFromRGB(0xff5955);
		case HO_REPORT_ORDER_UNCOMPLETED:    		//未完成
			return UIColorFromRGB(0xff5955);
		case HO_REPORT_ORDER_ACCEPTED:				//已受理
			return UIColorFromRGB(0x7687f1);
		case HO_EXTRA_ASS_ORDER_REPAIRED: 			//维修完成(外协)
		case HO_REPORT_ORDER_REPAIRED: 				//维修完成
			return UIColorFromRGB(0xffb94c);
		case HO_EXTRA_ASS_ORDER_CONFIRMED:			//确认完成(外协)
		case HO_REPORT_ORDER_CONFIRMED:				//确认完成
			return UIColorFromRGB(0x203d85);
		case HO_EXTRA_ASS_ORDER_DIR_CHECK:			//主任完成(外协)
			return UIColorFromRGB(0x7687f1);
		case HO_EXTRA_ASS_ORDER_DEAN_CHECK: 		//院长确认(外协)
			return UIColorFromRGB(0x4256d2);
		case HO_EXTRA_ASS_ORDER_CHECK_FAILED: 		//审核失败(外协)
			return UIColorFromRGB(0x6c807e);
		case HO_EXTRA_ASS_ORDER_CHECK_UNCOMPLETE: 	//未维修完成(外协)
			return UIColorFromRGB(0x6b6483);
		default:
			return UIColorFromRGB(0xc2c2c2);
	}
	return UIColorFromRGB(0xc2c2c2);
}

+ (double)getTimeStampByTimeStr:(NSString *)timeStampStr //@"yyyy-MM-dd HH:mm"
{
	NSDateFormatter *formate = [[[NSDateFormatter alloc] init] autorelease];
	[formate setDateFormat:@"yyyy-MM-dd mm:ss"];
	
	// I recommend setting a timezone because it will use the system timezone and that
	// can cause confusion with your data.
	[formate setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC ＋8"]];
	NSDate *date = [formate dateFromString:timeStampStr];
	return [date timeIntervalSince1970];
}

+ (BOOL)saveAudioIntLocal:(NSData *)data withFilePath:(NSString *)filePath
{
	LogNor(@"fileName:%@", filePath);
//	NSString *filePath = [HOUtils getFilePathWithFileName:fileName withFolderPath:[HOUtils getVoiceFolderPath] withExtension:type];
	LogNor(@"saveAudioIntLocalfilePath:%@", filePath);
	//  return YES;
	//    LogNor(@"data:%@", data);
	if ((data == nil) || (filePath == nil) || [filePath isEqualToString:@""]) {
		return NO;
	}
	@try {
		
		[data writeToFile:filePath atomically:YES];
		return  YES;
	}
	@catch (NSException *exception) {
		LogNor(@"保存音频失败");
		return NO;
	}
	return NO;
	
}

+ (NSString *)getWavAudioWithFileName:(NSString *)fileName
{
	return [HOUtils getFilePathWithFileName:fileName withFolderPath:[HOUtils getVoiceFolderPath] withExtension:FILE_TYPE_WAV];
}

+ (NSString *)getStatisticsTitle:(HO_STATISTICS_TYPE)type
{
	switch (type) {
  		case STATISTICS_TYPE_DEPT_WORKLOAD:
			return @"维修部门工作量统计";
		case STATISTICS_TYPE_PERSONAL_WORKLOAD:
			return @"个人工作量统计";
		case STATISTICS_TYPE_FAULT_AREA:
			return @"故障区域统计";
		case STATISTICS_TYPE_FAULT_TYPE:
			return @"故障类型统计";
		case STATISTICS_TYPE_FAULT_DEPARTMENT:
			return @"故障部门统计";
		case STATISTICS_TYPE_RESUBMIT:
			return @"返修率统计";
		case STATISTICS_TYPE_SATISFACTION:
			return @"满意度统计";
		case STATISTICS_TYPE_REPAIR_EFFECT:
			return @"维修效率统计";
		case STATISTICS_TYPE_PERSONAL:
			return @"个人得分统计";
			
  default:
			break;
	}
}

+ (NSString *)getTrimingString:(NSString *)content
{
	if(content == nil)
		return @"";
	NSString *valideContent = [content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	return valideContent;
}

+ (CGSize)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
{
	CGSize size = CGSizeZero;
	if (text) {
		CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];
		size = CGSizeMake(frame.size.width, frame.size.height + 1);
	}
	return size;
}

+ (NSAttributedString *)getAttributedStringWithFirstContent:(NSString*)firstContent withFirstColor:(UIColor *)firstColor withFirstFont:(UIFont *)firstFont
										 withSecondContent:(NSString*)secondContent withSecondColor:(UIColor *)secondColor withSecondFont:(UIFont *)secondFont
{
	if(firstContent == nil)
		firstContent = @"";
	
	if(secondContent == nil)
		secondContent = @"";
	
	NSString *strComplete = [NSString stringWithFormat:@"%@ %@",firstContent,secondContent];
	
	NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithString:strComplete];
	
	[attributedString addAttribute:NSForegroundColorAttributeName
							 value:firstColor
							 range:[strComplete rangeOfString:firstContent]];
	
	[attributedString addAttribute:NSFontAttributeName
							 value:firstFont
							 range:[strComplete rangeOfString:firstContent]];
	
	///----
	[attributedString addAttribute:NSForegroundColorAttributeName
							 value:secondColor
							 range:[strComplete rangeOfString:secondContent]];
	
	
	[attributedString addAttribute:NSFontAttributeName
							 value:secondFont
							 range:[strComplete rangeOfString:secondContent]];
	
	return attributedString;
}

+ (NSAttributedString *)getAttributedStringWithTitle:(NSString*)strFirst withContent:(NSString *)strSecond withColor:(UIColor *)color
{
	NSString *strComplete = [NSString stringWithFormat:@"%@ %@",strFirst,strSecond];
	
	NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithString:strComplete];
	
	[attributedString addAttribute:NSForegroundColorAttributeName
							 value:TEXT_COLOR_181818
							 range:[strComplete rangeOfString:strFirst]];
	
	if(color)
	{
		[attributedString addAttribute:NSForegroundColorAttributeName
								 value:color
								 range:[strComplete rangeOfString:strSecond]];
	}
	else
	{
		
		[attributedString addAttribute:NSForegroundColorAttributeName
								 value:TEXT_COLOR_666666
								 range:[strComplete rangeOfString:strSecond]];
	}
	return attributedString;
}

+ (void)callPhoneNumber:(NSString *)phoneNumber
{
	phoneNumber = nil;
	NSLog(@"telphone:%@", phoneNumber);
	if(phoneNumber == nil || phoneNumber.length == 0)
	{
//		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@""
//															message:@"无效号码，请联系总务科"
//														   delegate:nil
//												  cancelButtonTitle:@"确定"
//												  otherButtonTitles:nil];
//		[alertView show];
//		[alertView release];

//		return;
		phoneNumber = @"0573-86307299";
	}
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", phoneNumber]]];
}

//字典转data

+ (NSData *)returnDataWithDictionary:(NSDictionary *)dict
{
	
	NSMutableData * data = [[NSMutableData alloc] init];
	
	NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
	
	[archiver encodeObject:dict forKey:@"talkData"];
	
	[archiver finishEncoding];
	
	
	
	[data autorelease];
	
	[archiver autorelease];
	
	
	
	return data;
	
}

//路径文件转dictonary

+ (NSDictionary *)returnDictionaryWithDataPath:(NSString *)path
{
	
	NSData * data = [[NSMutableData alloc] initWithContentsOfFile:path];
	
	NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
	
	NSDictionary * myDictionary = [[unarchiver decodeObjectForKey:@"talkData"] retain];
	
	[unarchiver finishDecoding];
	
	//    NSLog(@"%@", myDictionary);
	
	[unarchiver autorelease];
	
	[data autorelease];
	
	
	
	return myDictionary;
	
}

// 读取本地JSON文件
+ (NSArray *)readLocalFileWithName:(NSString *)name
{
    // 获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"json"];
    // 将文件数据化
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    // 对数据进行JSON格式化并返回字典形式
    return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}

// 删除本地JSON文件
+ (BOOL)removeLocalFileWithName:(NSString *)name
{
    // 获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"json"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err;
    return [fileManager removeItemAtPath:path error:&err];
 
}
@end
